<!-- 车辆列表 -->
<template>
  <div class="car-list">
    <div ref="dgtools" class="filter-container">
      <div class="dgts-fm">
        <el-input
          style="width: 120px"
          placeholder="电话"
          clearable
          v-model="dg.ps.driverPhoneOrName">
        </el-input>

        <el-input
          style="width: 100px"
          placeholder="车牌号"
          clearable
          v-model="dg.ps.plateNum">
        </el-input>

        <el-input
          style="width: 100px"
          placeholder="座位数"
          clearable
          v-model="dg.ps.seats">
        </el-input>

        <el-select
          v-model="dg.ps.serviceType"
          :placeholder="'运营性质'"
          style="width: 100px"
          clearable>
          <el-option :label="'县际业务'" :value="'COUNTY_SER'"></el-option>
          <el-option :label="'市际业务'" :value="'CITY_SER'"></el-option>
          <el-option :label="'省际业务'" :value="'PROVINCE_SER'"></el-option>
        </el-select>

        <el-input
          style="width: 140px"
          placeholder="所属公司"
          clearable
          v-model="dg.ps.belongCompany">
        </el-input>

        <SelTeamGroup 
          :pname="'teamGroupId'" 
          @selItem="getSeledTeamGroup">
        </SelTeamGroup>

        <el-date-picker
          v-model="dg.ps.setime"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px">
        </el-date-picker>

        <el-select
          v-model="dg.ps.carStatus"
          :placeholder="'车辆状态'"
          style="width: 100px">
          <el-option :label="'全部车辆'" :value="''"></el-option>
          <el-option :label="'正常车辆'" :value="'NORMAL'"></el-option>
          <el-option :label="'报停车辆'" :value="'DESTORY'"></el-option>
          <el-option :label="'下线车辆'" :value="'DOWN'"></el-option>
        </el-select>
        <el-button 
          type="primary" 
          icon="el-icon-search" 
          @click="getDgList">
          搜索
        </el-button>

        <div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="getAddMdState(true)">
            新增
          </el-button>

          <el-button
            type="primary"
            icon="el-icon-edit-outline "
            @click="getUpdMdState(true)">
            修改
          </el-button>

          <el-button
            type="primary"
            icon=" el-icon-delete"
            @click="handleDelTableData">
            删除
          </el-button>

          <el-button
            type="primary"
            icon="el-icon-goods"
            @click="setStopOffLineMd({state: true})">
            报停下线
          </el-button>

          <el-button
            type="primary"
            @click="addEditPositionMdState(true)"
            icon="el-icon-s-shop">
            车辆停靠位置修改
          </el-button>

          <el-button
            type="primary"
            @click="setAddMaintenanceMd({state: true})"
            icon="el-icon-s-tools">
            维修保养
          </el-button>

          <el-button
            type="primary"
            icon="el-icon-s-marketing"
            @click="addCarLeaveMdState(true)">
            车辆预留
          </el-button>

          <el-button
            type="primary"
            @click="leaveCarListMdState(true)"
            icon="el-icon-s-fold">
            预留列表
          </el-button>

          <el-button
            type="primary"
            icon="el-icon-s-order"
            @click="macTaskMdState(true)">
            机务配件
          </el-button>

          <el-button
            type="primary"
            icon="el-icon-s-fold"
            @click="setSetMainDriverMd({state: true})">
            主驾设置
          </el-button>

          <el-button
            type="primary"
            icon="el-icon-close"
            @click="cancelMainDriver">
            取消主驾
          </el-button>

          <el-button 
            type="primary" 
            icon="el-icon-bottom"
            @click="U.qerror('抱歉，敬请期待...')">
            导出
          </el-button>
        </div>
      </div>

      <TableSelfSet
        v-if="dg.columns.length > 0"
        :tbTitle="'车辆列表'"
        :dgName="dg.dgName"
        :tbId="dg.tbName"
        :srcCols="dg.srcCols"
        :columns="dg.columns"
        @saveSet="saveTbSet"
      />
    </div>

    <el-table
      :ref="dg.tbName"
      :data="dg.list"
      row-key="id"
      :height="bodyHeight"
      border fit
      :row-class-name="rowClassName"
      @header-dragend="dragHeader"
      @selection-change="selRowChange">
      <el-table-column
        fixed="left"
        type="index"
        width="40"
        label="编号"
        align="center"
        :resizable="false">
      </el-table-column>

      <el-table-column
        fixed="left"
        type="selection"
        width="40"
        align="center"
        :resizable="false">
      </el-table-column>

      <el-table-column
        fixed="right"
        :label="'主驾驶员'"
        :prop="'mainDriver.realName'"
        :width="190"
        :align="'right'">
        <template slot-scope="{ row }">
          <span v-if="row.mainDriver">
            {{ row.mainDriver.driver.phone }}
            【{{ row.mainDriver.driver.realName }}】
          </span>
          <span v-else class="c-gray">未设置主驾驶员</span>
          <br />
          <el-button 
            size="mini" 
            @click="setRepairRecordTabsMd({state: true, row: row})">
            维修记录
          </el-button>
        </template>
      </el-table-column>

      <el-table-column
        v-for="(col, index) in dg.columns" 
        :key="index"
        :class-name="dg.dgName"
        :prop="col.field"
        :label="col.label"
        :width="col.width">
        <template slot-scope="{ row }">
          <template v-if="col.field == 'serviceType'">
            {{getServiceType(row.serviceType)}}
          </template>

          <template v-else-if="col.field == 'destoryTime'">
            <span>{{row.destoryTime | time('yyyy-MM-dd HH:mm')}}</span>
          </template>

          <template v-else-if="col.field == 'startTime'">
            <span>{{row.startTime | time('yyyy-MM-dd HH:mm')}}</span>
          </template>

          <template v-else-if="col.field == 'carColor'">
            <span>{{row.carColor ? row.carColor.slice(1, row.carColor.length - 1) : ''}}</span>
          </template>

          <template v-else-if="col.field == 'vehicleType'">
            {{getVehicleType(row.vehicleType)}}
          </template>

          <template v-else-if="col.field == 'isInternet'">
            {{row.isInternet == 1 ? "否" : "是"}}
          </template>

          <template v-else-if="col.field == 'repairTimeslot'">
            <!-- {{getSEtimeText(row.repairTimeslot)}} -->
            <span v-html="getSEtimeText(row.repairTimeslot)"></span>
          </template>

          <template v-else-if="col.field == 'downTime'">
            <span v-html="getTimeText(row.downTime)"></span>
          </template>

          <template v-else-if="col.field == 'status'">
            <el-button
              v-if="compareTime(row)"
              style="color: red; border-color: red"
              @click="setAddStopStartTimeMd({state: true, row: row})">
              报停启动
            </el-button>
            <span v-else v-html="getCarStatus(row)"></span>
          </template>

          <template v-else-if="col.field == 'powerSource'">
            {{getPowerSource(row.powerSource)}}
          </template>

          <template v-else-if="col.field == 'dockedLatLon'">
            <div>经度:{{ getlicensePhotoUrl(row.dockedLatLon)[0] || 0 }}</div>
            <div>纬度:{{ getlicensePhotoUrl(row.dockedLatLon)[1] || 0 }}</div>
          </template>

          <template v-else-if="col.field == 'runningArea'">
            {{getRunningArea(row.runningArea)}}
          </template>

          <template v-else-if="col.field == 'licensePhotoUrl'">
            <div v-if="row.licensePhotoUrl">
              <span v-if="getlicensePhotoUrl(row.licensePhotoUrl)[0]">
                正面：
                <img
                  style="width: 40px; height: 40px; vertical-align: middle"
                  :src="getlicensePhotoUrl(row.licensePhotoUrl)[0] || ''"
                  alt="暂无图片"
                />
              </span>
              <span v-if="getlicensePhotoUrl(row.licensePhotoUrl)[1]">
                反面：
                <img
                  style="width: 40px; height: 40px; vertical-align: middle"
                  :src="getlicensePhotoUrl(row.licensePhotoUrl)[1] || ''"
                  alt="暂无图片"
                />
              </span>
            </div>
          </template>

          <template v-else-if="col.field == 'customId'">
            {{getCustom(row.customId)}}
          </template>

          <template v-else-if="col.field == 'operationPhotoUrl'">
            <div v-if="row.operationPhotoUrl">
              <span v-if="getlicensePhotoUrl(row.operationPhotoUrl)[0]">
                正面：
                <img
                  style="width: 40px; height: 40px; vertical-align: middle"
                  :src="getlicensePhotoUrl(row.operationPhotoUrl)[0] || ''"
                  alt="暂无图片"
                />
              </span>
              <span v-if="getlicensePhotoUrl(row.operationPhotoUrl)[1]">
                反面：
                <img
                  style="width: 40px; height: 40px; vertical-align: middle"
                  :src="getlicensePhotoUrl(row.operationPhotoUrl)[1] || ''"
                  alt="暂无图片"
                />
              </span>
            </div>
          </template>

          <template v-else-if="col.field == 'carPlateUrl'">
            <div v-if="row.carPlateUrl">
              <img
                v-if="getlicensePhotoUrl(row.carPlateUrl)[0]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carPlateUrl)[0] || ''"
                alt="暂无图片"
              />
              <img
                v-if="getlicensePhotoUrl(row.carPlateUrl)[1]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carPlateUrl)[1] || ''"
                alt="暂无图片"
              />
            </div>
          </template>

          <template v-else-if="col.field == 'carPhotoUrl'">
            <div v-if="row.carPhotoUrl">
              <img
                v-if="getlicensePhotoUrl(row.carPhotoUrl)[0]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carPhotoUrl)[0] || ''"
                alt="暂无图片"
              />
              <img
                v-if="getlicensePhotoUrl(row.carPhotoUrl)[1]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carPhotoUrl)[1] || ''"
                alt="暂无图片"
              />
              <img
                v-if="getlicensePhotoUrl(row.carPhotoUrl)[2]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carPhotoUrl)[2] || ''"
                alt="暂无图片"
              />
            </div>
          </template>

          <template v-else-if="col.field == 'carLwh'">
            <div>长:{{ getlicensePhotoUrl(row.carLwh)[0] || 0 }}cm</div>
            <div>宽:{{ getlicensePhotoUrl(row.carLwh)[1] || 0 }}cm</div>
            <div>高:{{ getlicensePhotoUrl(row.carLwh)[2] || 0 }}cm</div>
          </template>

          <template v-else-if="col.field == 'carInterUrl'">
            <div v-if="row.carInterUrl">
              <img
                v-if="getlicensePhotoUrl(row.carInterUrl)[0]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carInterUrl)[0] || ''"
                alt="暂无图片"
              />
              <img
                v-if="getlicensePhotoUrl(row.carInterUrl)[1]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carInterUrl)[1] || ''"
                alt="暂无图片"
              />
              <img
                v-if="getlicensePhotoUrl(row.carInterUrl)[2]"
                style="width: 40px; height: 40px; vertical-align: middle"
                :src="getlicensePhotoUrl(row.carInterUrl)[2] || ''"
                alt="暂无图片"
              />
            </div>
          </template>

          <template v-else-if="col.field == 'carTrunkLwh'">
            <div>长:{{ getlicensePhotoUrl(row.carTrunkLwh)[0] || 0 }}cm</div>
            <div>宽:{{ getlicensePhotoUrl(row.carTrunkLwh)[1] || 0 }}cm</div>
            <div>高:{{ getlicensePhotoUrl(row.carTrunkLwh)[2] || 0 }}cm</div>
          </template>

          <template v-else>{{ getColVal(row, col.field) }}</template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="dg.total > 0"
      :total="dg.total"
      :page.sync="dg.ps.page"
      :limit.sync="dg.ps.rows"
      @pagination="getDgList"
    />

    <!-- <RepairRecord
      v-if="repairRecordMd.state"
      :myData="repairRecordMd"
      @myClick="setRepairRecordMd"
      @reloadDg="getDgList"
    /> -->

    <RepairRecordTabs
      v-if="repairRecordTabsMd.state"
      :myData="repairRecordTabsMd"
      @myClick="setRepairRecordTabsMd"
      @reloadDg="getDgList"
    />

    <AddCar
      v-if="md.add.state"
      :state="md.add.state"
      @getMdaaState="getAddMdState"
      @reloadDg="getDgList"
      :editId="editId"
    />

    <AddMainDriver
      v-if="setMainDriverMd.state"
      :mdTitle="'设置-车辆主驾'"
      :myData="setMainDriverMd"
      @myClick="setSetMainDriverMd"
    />

    <AddStopOffLine
      v-if="stopOffLineMd.state"
      :myData="stopOffLineMd"
      @myClick="setStopOffLineMd"
      @reloadDg="getDgList"
    />

    <AddStopTimeStart
      v-if="addStopStartTimeMd.state"
      :myData="addStopStartTimeMd"
      @myClick="setAddStopStartTimeMd"
      @reloadDg="getDgList"
    />

    <AddEditPosi
      v-if="md.addEditPosition.state"
      :state="md.addEditPosition.state"
      @addEditPositionMdState="addEditPositionMdState"
      :posiId="posiId"
      :backObj="dg.selRows[0]"
      @reloadDg="getDgList"
    />

    <AddMaintenance
      v-if="addMaintenanceMd.state"
      :myData="addMaintenanceMd"
      @myClick="setAddMaintenanceMd"
      @reloadDg="getDgList"
    />

    <AddCerNumberLeave
      v-if="md.carLeave.state"
      :state="md.carLeave.state"
      @addCarLeaveMdState="addCarLeaveMdState"
      :repairArrId="varListIds"
      :backObj="dg.selRows[0]"
      @reloadDg="getDgList"
    />

    <AddMainTask
      v-if="md.macTask.state"
      :state="md.macTask.state"
      @macTaskMdState="macTaskMdState"
      :taskId="taskId"
      @reloadDg="getDgList"
    />

    <AddLeaveCarList
      v-if="md.leaveCarList.state"
      :state="md.leaveCarList.state"
      @leaveCarListMdState="leaveCarListMdState"
      :leaveId="leaveId"
      @reloadDg="getDgList"
    />

    
    <!-- <UpdGroup    AddStopOffLine 
            v-if="md.upd.state"  
            :state="md.upd.state" 
            :data="md.upd.data"
            @getMdState="getUpdMdState" 
            @reloadDg="getDgList"
        /> -->

  </div>
</template>

<script>
import { mapGetters } from "vuex";
import DataGridBase from "@/views/mixins/DataGridBase";
import DataGridResize from "@/views/mixins/DataGridResize";
import TableSelfSet from "@/components/TableSelfSet";
import Pagination from "@/components/Pagination";

import SelTeamGroup from '@/components/SelTeamGroup';
// import RepairRecord from "./repair-record";
import RepairRecordTabs from "./repair-record-tabs";
import AddCar from "./add-car";
import AddMainDriver from "./add-mian-driver";
import AddStopOffLine from "./add-stop-offline";
import AddStopTimeStart from "./add-stop-time";
import AddEditPosi from "./add-edit-posi";
import AddMaintenance from "./add-maintenance";
import MyMap from "./MyAmap";
import AddCerNumberLeave from "./add-carnumber-leave";
import AddMainTask from "./add-maichine-task";
import AddLeaveCarList from "./add-leavecar-list";
// import UpdCar from './upd-car';

import { getGroupDict } from "@/api/services/common.service";
import * as logisticsSer from "@/api/services/logistics.service";

export default {
  name: "CarList",
  mixins: [DataGridBase, DataGridResize],
  components: {
    RepairRecordTabs,
    AddMainTask,
    TableSelfSet,
    Pagination,
    SelTeamGroup,
    // RepairRecord,
    AddCar,
    AddMainDriver,
    AddStopOffLine,
    AddStopTimeStart,
    MyMap,
    AddMaintenance,
    AddEditPosi,
    AddCerNumberLeave,
    AddLeaveCarList,
  },
  computed: {
    ...mapGetters(["lunitNum"]),

    /** 获取-车辆性质 */
    getCusUsage() {
      return function (val) {
        switch (val) {
          case "TRAVELTRANS":
            return "旅游客运";
          case "TRAVELTRANSNET":
            return "旅游客运上网";
          case "HIGHWAYTRANS":
            return "公路客运";
          case "HIGHWAYTRANSNET":
            return "公路客运上网";
          case "LEASE":
            return "租赁";
          default:
            return "";
        }
      };
    },
    /** 获取-车辆类型 */
    getVehicleType() {
      return function (val) {
        switch (val) {
          case "BUS":
            return "大巴车";
          case "MINIBUS":
            return "中巴车";
          case "MPV":
            return "商务车";
          case "SUV":
            return "越野车";
          case "CAR":
            return "轿车";
          case "BMPV":
            return "保姆车";
          default:
            return "";
        }
      };
    },
    /** 获取-运营类型 */
    getServiceType() {
      return function (val) {
        switch (val) {
          case "COUNTY_SER":
            return "县际业务";
          case "CITY_SER":
            return "市际业务";
          case "PROVINCE_SER":
            return "省际业务";
          default:
            return "";
        }
      };
    },
    /** 获取-起止时间文本 */
    getSEtimeText() {
      return function (val) {
        if (val) {
          let stime = val.split("/")[0];
          stime = stime.substring(0, stime.lastIndexOf(":"));
          let etime = val.split("/")[1];
          etime = etime.substring(0, etime.lastIndexOf(":"));
          return `开始：${stime}<br />结束：${etime}`;
        }
        return "";
      };
    },
    /** 获取-时间文本 */
    getTimeText() {
      return function (val) {
        if (val) {
          let time = val.split("/")[0];
          time = time.substring(0, time.lastIndexOf(":"));
          return `${time}`;
        }
        return "";
      };
    },
    /** 获取-动力来源 */
    getPowerSource() {
      return function (val) {
        switch (val) {
          case "DIESEL":
            return "柴油";
          case "GASOLINE":
            return "汽油";
          case "CNG":
            return "CNG";
          case "NEWENERGY":
            return "新能源";
          default:
            return "";
        }
      };
    },
    /** 获取-可跑区域 */
    getRunningArea() {
      return function (val) {
        switch (val) {
          case 1:
            return "省际包车";
          case 2:
            return "市际包车";
          case 3:
            return "县际包车";
          default:
            return "";
        }
      };
    },

    // 获取车辆颜色
    getCarColor() {
      return function (val) {
        switch (val) {
          case "RED":
            return "红色";
          case "YELLOW":
            return "黄色";
          case "GREEN":
            return "绿色";
          case "BLUE":
            return "蓝色";
          case "WHITE":
            return "白色";
          case "VIOLET":
            return "紫色";
          case "BLACK":
            return "黑色";
          default:
            return "";
        }
      };
    },
    /** 获取-车辆状态 */
    getCarStatus() {
      const that = this, U = that.U;
      
      return function (o) {
        let status = "";

        // 当前时间毫秒
        let nowtime = new Date().getTime();

        // 维修时间、报停时间、下线时间都[不存在]
        // if(!o.repairTimeslot && !o.destoryTimeslot && !o.downTime){
        //     status = '<b class="c-green">正常</b>';
        // }

        // 存在：下线时间
        if (o.downTime) {
          let xxtime = U.str2date(o.downTime).getTime();
          // 当前时间 >= 下线时间，则表示：下线
          if (nowtime >= xxtime) status = '<b class="c-gray">下线</b>';
        }

        // 存在：维修时间
        if (o.repairTimeslot) {
          let wxStime = U.str2date(o.repairTimeslot.split("/")[0]).getTime();
          let wxEtime = U.str2date(o.repairTimeslot.split("/")[1]).getTime();
          // 当前时间 >= 维修开始时间 && 当前时间 <= 维修结束时间，则表示：维修
          if (nowtime >= wxStime && nowtime <= wxEtime) status = '<b class="c-yellow">维修</b>';
        }

        // 存在：报停时间  当前时间 大于报停时间
        if (o.destoryTime) {
          // if(4) {
          // 当前时间> 4 ==> 正常
          //   当前时间<  4 ===> 报停；
          // }else {
          //   当前时间 > 2	启动报停
          // }
          if (o.startTime) {
            const Stime = new Date(o.startTime).getTime();
            // 有报停时间 无报停启动时间；--- 报停
            if (nowtime >= Stime) {
              status = '<b class="c-green">正常</b>';
            } else {
              status = '<b class="c-red">报停</b>';
            }
          }
          // let btStime = U.str2date(o.destoryTimeslot.split("/")[0]).getTime();
          // let btEtime = U.str2date(o.destoryTimeslot.split("/")[1]).getTime();
          // const btStime = new Date(o.destoryTime).getTime();
          // const btEtime = new Date(o.destoryTime).getTime();
          // 当前时间 >= 报停开始时间 && 当前时间 <= 报停结束时间，则表示：报停
          // if (nowtime >= btStime && nowtime <= btEtime)
          // if (nowtime - btStime > 0)
          //   // '<button class="c-red" ></button>';
          //   status =
          //     "<button click='handleStart' class='c-red'>" +
          //     "报停启动" +
          //     "</a>";
        }

        // 维修时间、报停时间、下线时间都[存在]
        if (o.repairTimeslot && o.destoryTime && o.downTime) {
          let wxStime = U.str2date(o.repairTimeslot.split("/")[0]).getTime();
          let wxEtime = U.str2date(o.repairTimeslot.split("/")[1]).getTime();
          let btStime = U.str2date(o.destoryTimeslot.split("/")[0]).getTime();
          let btEtime = U.str2date(o.destoryTimeslot.split("/")[1]).getTime();
          let xxtime = U.str2date(o.downTime).getTime();

          // 当前时间
          if (nowtime >= xxtime && ((wxStime < nowtime && nowtime < wxEtime) || (btStime < nowtime && nowtime < btEtime))) {
            status = '<b class="c-gray">下线</b>';
          } else if (nowtime >= xxtime && ((wxStime > nowtime && nowtime > wxEtime) || (btStime > nowtime && nowtime > btEtime))) {
            status = '<b class="c-gray">下线</b>';
          } else if (nowtime < xxtime && wxStime < nowtime && nowtime < wxEtime) {
            status = '<b class="c-yellow">维修</b>';
          } else if (nowtime < xxtime && btStime < nowtime && nowtime < btEtime) {
            status = '<b class="c-red">报停</b>';
          }
          

          // else if((nowtime < xxtime) && ((wxStime > nowtime && nowtime > wxEtime) || (btStime > nowtime && nowtime > btEtime))){
          //     status = '<b class="c-green">正常</b>';
          // }else if((nowtime < xxtime) && ((wxStime < nowtime && nowtime > wxEtime) || (btStime < nowtime && nowtime > btEtime))){
          //     status = '<b class="c-green">正常</b>';
          // }
        }

        if (!status) status = '<b class="c-green">正常</b>';

        return status;
      };
    },
  },
  data() {
    let cols = [
      { label: "座位数", field: "seats", width: 60 },
      { label: "车牌号", field: "plateNum", width: 70 },
      { label: "营运性质", field: "serviceType", width: 70 },
      { label: "车辆颜色", field: "carColor", width: 100 },
      { label: "本公司购买日期", field: "ownPurchaseDate", width: 100 },
      { label: "行驶证购车日期", field: "purchaseDate", width: 100 },
      { label: "车辆类型", field: "vehicleType", width: 70 },
      { label: "是否上网", field: "isInternet", width: 70 },
      { label: "添加时间", field: "addTime", width: 130 },
      { label: "维修时间", field: "repairTimeslot", width: 140 },
      { label: "下线时间", field: "downTime", width: 140 },
      { label: "报停后启动时间", field: "startTime", width: 110 },
      { label: "报停时间", field: "destoryTime", width: 110 },
      { label: "车辆状态", field: "status", width: 80 },
      { label: "动力来源", field: "powerSource", width: 70 },
      { label: "正常油耗", field: "fuel", width: 70 },
      { label: "方位", field: "direction", width: 60 },
      { label: "停靠地址全称", field: "dockedAddress", width: 140 },
      { label: "停靠地址简称", field: "simpleDockedAddress", width: 120 },
      { label: "停靠地址经纬度", field: "dockedLatLon", width: 140 },
      { label: "驾照需求", field: "drivingType", width: 140 },
      // {label: '所属公司简称', field: 'simpleDockedAddress', width: 140},
      { label: "可跑区域", field: "runningArea", width: 140 },
      { label: "驾驶证正反面", field: "licensePhotoUrl", width: 120 },
      // {label: '注册上户日期', field: 'purchaseDate', width: 140},
      { label: "车辆年限", field: "carYear", width: 100 },
      // {label: '过户日期', field: 'ownPurchaseDate', width: 140},
      { label: "挂靠客户", field: "customId", width: 140 },
      { label: "运营证正反面", field: "operationPhotoUrl", width: 120 },
      { label: "年审日期", field: "inspectDate", width: 140 },
      { label: "车辆名牌", field: "carPlateUrl", width: 140 },
      { label: "发动机号", field: "engineNum", width: 140 },
      { label: "车架号", field: "vinNum", width: 140 },
      { label: "续航里程", field: "mileage", width: 140 },
      { label: "车辆外观", field: "carPhotoUrl", width: 140 },
      { label: "车辆长宽高", field: "carLwh", width: 140 },
      { label: "车辆内饰", field: "carInterUrl", width: 140 },
      { label: "车辆行李箱个数", field: "carTrunkCount", width: 140 },
      { label: "车辆行李箱尺寸", field: "carTrunkLwh", width: 140 },
      { label: "不可跑区域", field: "notRunningArea", width: 140 },
    ];

    return {
      // 文件地址前缀
      fileBaseUrl: this.C.fileBaseUrl,
      // 修改位置id
      posiId: "", 
      dg: {
        dgName: "dg",
        tbName: "carListTb",
        total: 0,
        list: [],
        srcCols: cols,
        columns: [],
        selRows: [],
        ps: {
          // 过滤参数
          page: 1, rows: 20,
          // 单位编号
          unitNum: "",
          // 驾驶员手机号
          driverPhoneOrName: "", 
          // 车牌号
          plateNum: "",
          // 座位数 
          seats: "", 
          // 所属挂靠公司名称
          belongCompany: "", 
          carUsage: "",
          // 小组ID 可以多选
          deptId: [], 
          // 起止日期
          setime: "",
          // 开始日期
          startTime: "",
          // 结束日期
          endTime: "",
          // 车辆状态
          carStatus: "", 
          // 停靠位置
          stayStation: "", 
          // 车辆类型
          vehicleType: "",
          // 车辆颜色 
          carColor: "", 
          // 运营性质
          serviceType: "",
          // 能否上网  0 上网； 1 不能上网 
          isInternet: "", 
        },
        editArr: null,
        total: 0,
        list: [],
        columns: cols,
        dropCol: this.U.scopy(cols),
        shFields: this.U.scopy(cols),
        // 展开的行keys数组
        rowExpands: [],
      },
      md: {
        // 弹框数据
        add: { state: false }, // 添加车辆
        // addStopTimeStart: { state: false }, // 启动时间
        addEditPosition: { state: false }, // 选择地图
        // addMaintenance: { state: false }, // 维修预约
        upd: { state: false }, // 修改车辆
        macTask: { state: false }, // 修改车辆
        carLeave: { state: false }, // 车辆预留
        // repairRecord: { state: false }, // 维修记录
        leaveCarList: { state: false }, // 维修记录
      },

      // 维修记录tab-弹框
      repairRecordTabsMd: {state: false},
      // 报停下线-弹框
      stopOffLineMd: {state: false},
      // 报停启动-弹框
      addStopStartTimeMd: {state: false},
      // 设置主驾-弹框
      setMainDriverMd: {state: false},
      // 维修预约-弹框
      addMaintenanceMd: {state: false},


      groupList: [], // 小组列表
      arrList: [], // 驾驶证正反面
      editId: "",
      stopStartTimeId: "", // 启动报停的ID
      repairArrId: [], // 维修的报停
      varListIds: [], // 车辆预留选择的数据
      taskId: null, // 机务设置的taskId
      leaveId: null, // 车辆预留列表ID
      recordData: null,
    };
  },
  created() {
    const that = this;

    that.initTbSetData(that.dg.dgName);

    // 赋值单位编号
    that.dg.ps.unitNum = that.lunitNum;
    that.getDgList();
  },
  methods: {
    // 获取驾驶证正面 反面
    getlicensePhotoUrl(val) {
      let url = (val || "").split(",");
      if(url) this.fileBaseUrl + url;
      return url;
    },
    // 获取选中-小队、小组数据
    getSeledTeamGroup(e){
      this.U.setFmArr(this.dg.ps.deptId, e.val);
    },
    // 是否显示-报停启动按钮
    compareTime(row) {
      const that = this, U = that.U;

      if (!row) return;
      
      // 当前时间
      let currTime = that.$moment();

      // 同时存在报停时间和启动时间，则表示至少报停一次
      if(row.destoryTime && row.startTime){
        // 报停时间
        let destoryTime = that.$moment(row.destoryTime);
        // 启动时间
        let startTime = that.$moment(row.startTime);
        
        // 启动时间在报停时间之前，说明至少是第二次报停
        if(startTime.isBefore(destoryTime)){
          // 报停时间在当前时间之前，则显示报停启动按钮
          if(destoryTime.isBefore(currTime)) return true;
        }else{
          // 启动时间在当前时间之后，则显示报停启动按钮
          if(startTime.isAfter(currTime)) return true;
        }
      }else if(row.destoryTime && !row.startTime){// 只有报停时间，则表示当前是第一次报停
        // 报停时间
        let destoryTime = that.$moment(row.destoryTime);

        // 报停时间在当前时间之前，则显示报停启动按钮
        if(destoryTime.isBefore(currTime)) return true;
      }

      return false;
    },
    // 停靠位置修改；
    getMapData(e) {
      if (!e) return;
      const { address, lng, lat } = e;
      
      this.fm.ps.applyAddress = address;
      this.fm.ps.applyLatLon = `${lng},${lat}`;
      this.fm.pd = e;
      this.md.addEditPosition.state = false;
    },
    // 显示/隐藏-维修记录tab-弹框
    setRepairRecordTabsMd(e) {
      const that = this, md = that.repairRecordTabsMd;

      if(!e.state){
        md.obj = null;
        md.state = false;
      }else{
        md.obj = e.row;
        md.state = true;
      }
    },
    // 添加预留列表
    leaveCarListMdState(e) {
      const that = this, U = that.U, rows = that.getSeledRows();
      
      if(rows.length > 1){
        U.qerror('只能选择一条数据');
      }else {
        if(rows.length == 1){
          let row = rows[0];
          that.leaveId = row.id;
        }

        that.md.leaveCarList.state = e;
      }
    },
    // 显示/隐藏-主驾设置-弹框
    setSetMainDriverMd(e) {
      const that = this, U = that.U, md = that.setMainDriverMd, rows = that.getSeledRows();
      
      if(!e.state){
        if(!e.ps){
          md.state = false;
        }else{// 提交-设置车辆主驾
          let ps = {
            // 车辆ID
            id: md.obj.id,
            // 驾驶员用户名
            uname: e.ps.driver.uname,
          };
          logisticsSer.setCarDriver(ps).then((res) => {
            if (res.code != 1) {
              U.qerror(res.msg);
            } else {
              U.qsuccess(res.msg);

              // 关闭弹框、清空数据、刷新列表
              md.obj = null;
              md.state = false;
              that.getDgList();
            }
          });
        }
      }else{
        if (rows.length !== 1) {
          U.qerror("请选择一条数据");
        }else{
          let row = rows[0];
          if(row.mainDriver){
            md.obj = {id: row.id, realName: row.mainDriver.driver.realName, phone: row.mainDriver.driver.phone};
          }else{
            md.obj = {id: row.id, realName: '', phone: ''};
          }
          md.state = true;
        }
      }
    },
    // 取消主驾
    cancelMainDriver(){
      const that = this, U = that.U, rows = that.getSeledRows();

      if (rows.length != 1) {
        U.qerror("请选择一条数据");
      }else{
        let row = rows[0];
        U.qconfim(`确认取消所选车辆的主驾吗？`).then(r => {
          if(r){
            logisticsSer.setCarDriver({id: row.id, uname: '' }).then(res => {
              if(res.code !== 1){
                U.qerror(res.msg);
              }else{
                U.qsuccess(res.msg);

                // 刷新列表
                that.getDgList();
              }
            });
          }
        });
      }
    },
    addStopTimeStartMdState(e) {
      this.getDgList();
      this.md.addStopTimeStart.state = e;
    },
    addEditPositionMdState(e) {
      const that = this, U = that.U, rows = that.getSeledRows(), md = that.md.addEditPosition;

      if (rows.length !== 1) {
        U.qerror("请选择一条数据");
      }else{
        that.posiId = rows[0].id;
        md.state = e;
      }
    },
    // 显示/隐藏-维修保养-弹框
    setAddMaintenanceMd(e) {
      const that = this, U = that.U, rows = that.getSeledRows(), md = that.addMaintenanceMd;
      
      if(!e.state){
        md.repairIdArr = null;
        md.state = false;
      }else{
        if (rows.length == 0) {
          U.qerror("请至少选择一条数据");
        }else{
          md.repairIdArr = rows.map(it => it.id);
          md.state = true;
        }
      }
    },
    // 机务设置
    macTaskMdState(e) {
      const that = this, U = that.U, rows = that.getSeledRows(), md = that.md.macTask;
      
      if (rows.length == 0) {
        U.qerror("请至少选择一条数据");
      }else{
        that.taskId = rows[0];
        md.state = e;
      }
    },
    // 车辆预留
    addCarLeaveMdState(e) {
      const that = this, U = that.U, rows = that.getSeledRows(), md = that.md.carLeave;

      that.varListIds = rows.map((item) => item.id);
      md.state = e;
    },
    // 开启/隐藏-报停下线-弹框
    setStopOffLineMd(e) {
      const that = this, U = that.U, md = that.stopOffLineMd, rows = that.getSeledRows();

      if(!e.state){
        md.obj = null;
        md.state = false;
      }else{
        if(rows.length !== 1){
          U.qerror(`${rows.length == 0 ? '请' : '只能'}选择一条数据`);
        }else{
          md.obj = rows[0];
          md.state = true;
        }
      }
    },

    // 开启/隐藏-报停启动-弹框
    setAddStopStartTimeMd(e) {
      const that = this, md = that.addStopStartTimeMd;

      if(!e.state){
        md.obj = null;
        md.state = false;
      }else{
        md.obj = e.row;
        md.state = true;
      }
    },
    
    // 获取挂靠公司
    getCustom(value) {
      if (value) {
        return value.unitName || "";
      }
    },

    /**
     * 把每一行bai的索引放入进row
     */
    rowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    /**
     * 获取-车辆分页列表
     */
    getDgList() {
      const that = this, ps = that.U.scopy(that.dg.ps);
      // 处理参数
      const setime = ps.setime;
      if (setime) {
        ps.startTime = setime[0];
        ps.endTime = setime[1];
        delete ps.setime;
      }
      // 处理选择小组数据
      ps.groupDeptId = ps.deptId.join(',');

      logisticsSer.vehicleListFind(ps).then((res) => {
        if (res.code == 1) {
          let { data = [], count = 0 } = res;
          let list = data;
          list.forEach((it) => {it.dgName = this.dg.dgName;});
          that.dg.list = list;
          that.dg.total = count;
        }
      });
    },

    /**
     * 删除表格数据
     */
    handleDelTableData() {
      let that = this, U = that.U, rows = that.getSeledRows();

      if (rows.length !== 1) {
        U.qerror("请选择一条需要删除的数据");
      }else{
        const { id } = rows[0];
        logisticsSer.carListDelete({ id }).then((res) => {
          if (res.code != 1) {
            U.qerror(res.msg);
          } else {
            U.qsuccess(res.msg);

            that.getDgList();
          }
        });
      }
    },
    /**
     * 打开添加弹框
     */
    getAddMdState(e) {
      this.dg.selRows = [];
      this.editId = "";
      this.md.add.state = e;
      if(!e){// 关闭弹框，清除选中行
        this.$refs[this.dg.tbName].clearSelection();
      }
    },
    /**
     * 打开修改弹框
     * @param e 弹框显隐状态
     */
    getUpdMdState(e) {
      const that = this, U = that.U, rows = that.getSeledRows();

      if (e == false) {
        // 关闭弹框
        that.md.upd.state = e;
        this.$refs[this.dg.tbName].clearSelection();
      } else {
        // 打开弹框
        if (rows.length !== 1) {
          U.qerror("请选择一条数据");
        } else {
          that.editId = rows[0].id;
          that.md.add.state = true;
        }
      }
    },


  },
};
</script>

<style scoped>
</style>